﻿#if DEBUG
    #define _DEBUG_LOG_CONSOLE_OUTPUT_
#endif
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace EasyLog
{
    public enum LogLevel
    {
        LogLevel_Release,
        LogLevel_Debug
    }
    public class Log
    {
        private string m_logfile = string.Empty;
        private LogLevel m_loglevel;
        private string m_logpre = string.Empty;
        private Log()
        {
        }
        public Log(string filepath, LogLevel lev = LogLevel.LogLevel_Debug, string logPre = "日志")
        {
            if (Directory.Exists(filepath))//如果是目录，就创建日志文件
            {
                m_logfile = filepath + @"\log_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".log";
                File.Create(m_logfile).Close();
            }
            else if (!File.Exists(filepath))//如果不是目录，并且文件也不存在
            {
                if (!Directory.Exists(Path.GetDirectoryName(filepath)))//如果目录不存在，那么就指定在程序目录下创建
                {
                    Directory.CreateDirectory(System.Environment.CurrentDirectory + @"\log");
                    m_logfile = System.Environment.CurrentDirectory +
                                  @"\log\log_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".log";
                    File.Create(m_logfile).Close();
                }
                else//如果目录正确，但是文件不存在，就创建
                {
                    m_logfile = filepath;
                    File.Create(m_logfile).Close();
                }
            }
            else//如果文件存在，就不创建
            {
                m_logfile = filepath;
            }
            m_loglevel = lev;
            m_logpre = logPre+":";
        }
        public void AppendStr(string msg, LogLevel lev = LogLevel.LogLevel_Debug)
        {
            try
            {
                StreamWriter sw = File.AppendText(m_logfile);
                 string msgoutmsg = m_logpre+ DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss: ") + msg;
                 sw.WriteLine(msgoutmsg);
#if  _DEBUG_LOG_CONSOLE_OUTPUT_//如果定义了，就不在console中输出
                 Console.WriteLine(msgoutmsg);
#endif
                 sw.Close();
            }
            catch
            {
            }
        }
    }
}
